#include <iostream>
#include <memory>
#include <vector>
#include <cassert>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "HttpServer.hpp"
#include "Util.hpp"

// 一般http都要有自己的web根目录
#define ROOT "./wwwroot" // ./wwwroot/index.html
// 如果客户端只请求了一个/,我们返回默认首页
#define HOMEPAGE "index.html"

static void Usage(const std::string& proc)
{
    std::cout << "\nUsage: " << proc << ": port" << std::endl;
}


void HandlerHttpRequest(int sockfd)
{
   // 1. 读取请求 for test
    char buffer[10240];
    ssize_t s = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
    if (s > 0)
    {
        buffer[s] = 0;
        std::cout << buffer << "--------------------\n" << std::endl;
    }

    // 服务器: 自己构建一个http的响应
    // std:: string HttpResponce = "HTTP/1.1 200 OK\r\n"; // 状态行
    // HttpResponse += "\r\n";  // 空行 
    // HttpResponse += "<html><h3>宋增</h3><html>"; // 文本内容
    // send(sockfd, HttpResponse.c_str(), HttpResponse.size(),0);


    std::vector<std::string> vline; // 存放所有/r/n 分开的字符串
    Util::cutString(buffer, "\n", &vline);

    std::vector<std::string> vblock;
    Util::cutString(vline[0], " ", &vblock); 

    std::string file = vblock[1];
    std::string target = ROOT;

    if(file == "/") file = "/index.html";
    target += file;

    std::string content;
    std::ifstream in(target);
    if(in.is_open())
    {
        std::string line;
        while(std::getline(in, line))
        {
            content += line;
        }
        in.close();
    }

    std::string HttpResponse;
    std::string HttpResponse;
    if(content.empty()) 
    {
        HttpResponse = "HTTP/1.1 301 Moved Permanently\r\n";
        HttpResponse += "Location: http://120.78.126.148:8081/a/b/404.html\r\n";
    }
    else 
    {
        HttpResponse = "HTTP/1.1 200 OK\r\n";
        HttpResponse += ("Content-Type: text/html\r\n"); 
        HttpResponse += ("Content-Length: " + std::to_string(content.size()) + "\r\n");
        HttpResponse += "Set-Cookie: 这是一个cookie\r\n";
    }
    HttpResponse += "\r\n";
    HttpResponse += content;

    send(sockfd, HttpResponse.c_str(), HttpResponse.size(),0);

}


// ./HttpServer port
int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::unique_ptr<HttpServer> httpserver(new HttpServer(atoi(argv[1]), HandlerHttpRequest));
    httpserver->Start();
    return 0;
}


#include "Sock.hpp"

int main()
{
    Sock sock;
    int listensock = sock.Socket();
    sock.Bind(listensock, 8080);
    sock.Listen(listensock);

    while(true)
    {
        std::string clientip;
        uint16_t clientport;
        int sockfd = sock.Accept(listensock, &clientip, &clientport);
        if(sockfd > 0)
        {
            std::cout << "[" << clientip << ":" << clientport << "]# " << sockfd << std::endl;
        }

        sleep(10);
        close(sockfd);
    }
}
